import {ecs} from "db://oops-framework/libs/ecs/ECS";
import {AsyncQueue, NextFunction} from "db://oops-framework/libs/collection/AsyncQueue";
import {oops} from "db://oops-framework/core/Oops";
import {UIID} from "db://assets/script/game/common/config/gameUiConfig";
import {LoadingViewComp} from "db://assets/script/game/initialize/view/loadingViewComp";
import {InitResComp} from "db://assets/script/game/initialize/comp/initResComp";
import {Initialize} from "db://assets/script/game/initialize/entity";

export class InitResSystem extends ecs.ComblockSystem implements ecs.IEntityEnterSystem {
    filter(): ecs.IMatcher {
        return ecs.allOf(InitResComp)
    }

    entityEnter(entity: Initialize): void {
        const queue = new AsyncQueue()
        this.loadBundle(queue)
        this.loadCustom(queue)
        this.loadLanguage(queue)
        this.loadCommon(queue)
        this.onComplete(queue, entity)
        queue.play()
    }

    // 加载远程资源配置
    private loadBundle(queue: AsyncQueue) {
        queue.push(async (next: NextFunction, params: any, args: any) => {
            // 设置外部资源包名(config.json bundle 下的 name字段)
            oops.res.defaultBundleName = oops.config.game.bundleName
            if (oops.config.game.bundleEnable) {
                console.log("加载远程资源")
                await oops.res.loadBundle(oops.config.game.bundleServer, oops.config.game.bundleVersion)
            } else {
                console.log("加载本地资源")
                await oops.res.loadBundle(oops.config.game.bundleName)
            }
            next()
        })
    }

    // 加载自定义内容（可选）
    private loadCustom(queue: AsyncQueue) {

    }

    // 加载化语言包（可选）
    private loadLanguage(queue: AsyncQueue) {
        queue.push((next, params, args) => {
            // 设置默认语言
            let lang = oops.storage.get("language")
            if (lang == null) {
                lang = "zh"
                oops.storage.set("language", lang)
            }
            // 加载语言包资源
            oops.language.setLanguage(lang, next)
        })
    }

    // 加载公共资源
    private loadCommon(queue: AsyncQueue) {
        queue.push((next, params, args) => {
            oops.res.loadDir("common", next)
        })
    }

    // 加载完成进入游戏内容加载界面
    private onComplete(queue: AsyncQueue, entity: Initialize) {
        queue.complete = async () => {
            const node = await oops.gui.openAsync(UIID.loading)
            if (node) {
                entity.add(node.getComponent(LoadingViewComp) as ecs.Comp)
            }
            entity.remove(InitResComp)
        }
    }
}